package com.tsingteng.cosfun.base;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.PowerManager;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;


import com.tsingteng.cosfun.R;
import com.tsingteng.cosfun.common.Config;
import com.tsingteng.cosfun.helper.ActivityManagers;
import com.tsingteng.cosfun.helper.DialogHelper;

import com.tsingteng.cosfun.utils.LogUtils;
import com.tsingteng.cosfun.utils.NotchUtil;
import com.tsingteng.cosfun.utils.ToastUtils;
import com.umeng.analytics.MobclickAgent;
import com.umeng.message.PushAgent;
import com.umeng.message.entity.UMessage;

import java.util.Map;

import butterknife.ButterKnife;
import butterknife.Unbinder;


/**
 * 描述:基类的activity
 * 创建人: 肖利
 * 时间: 2018/7/30
 * qq: (872179966)
 */

public abstract class BaseActivity extends AppCompatActivity {
    RelativeLayout mRlTitle;
    FrameLayout frameLayout;
    private Unbinder unbinder;
    private Dialog mLoadingDialog;
    private Dialog mHintDialog;
    private PowerManager.WakeLock wl;
    private PowerManager pm;
    private static  Handler handler= new Handler();
    public   boolean isFullScreen = false;//是否显示全屏
    public boolean isFound = false;
    public boolean isUpKeyBord = false;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //如果系统回收Activity,但是系统却保留了Fragment,当Activity被重新初始化,此时,系统保存的Fragment 的getActivity为空,所以要移除旧的Fragment,重新初始化新的Fragment
        if (savedInstanceState != null) {
            savedInstanceState.remove(Config.FRAGMENTS_TAG);
        }
        if (isUpKeyBord) {
            getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        }
        super.onCreate(savedInstanceState);
        LogUtils.i("BaseActivity", getClass().getSimpleName() + " onCreate("
                + (savedInstanceState == null ? "" : savedInstanceState) + ")");

        //得到上个页面传来的数据
        Intent intent = getIntent();
        if (intent != null) {
            getIntentData(intent);
        }
        if (isFullScreen) {//是否显示全屏(拍摄地方用)
            requestWindowFeature(Window.FEATURE_NO_TITLE);
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        }
        setContentView(R.layout.activity_base);
        frameLayout = (FrameLayout) findViewById(R.id.frameLayout);
        //初始化子类布局
        initContent(getLayoutId());
        //初始化消息框
        mLoadingDialog = DialogHelper.getLoadingDialog(this);
        mHintDialog = DialogHelper.getHintDialog(this);
        //管理屏幕常亮状态
        pm = (PowerManager) getSystemService(POWER_SERVICE);
        wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP,
                getResources().getString(R.string.app_name));
        bright();
        ActivityManagers.getInstance().addActivity(this);
//        setHideVirtualKey(getWindow());
        getWindow().getDecorView().setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener() {
            @Override
            public void onSystemUiVisibilityChange(int visibility) {
//                if (!isFound) {
//                    setHideVirtualKey(getWindow());
//                }
            }
        });
    }

    public void setHideVirtualKey(Window window){
        //保持布局状态
        int uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_STABLE|
                //布局位于状态栏下方
                View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION|
                //隐藏导航栏
                View.SYSTEM_UI_FLAG_HIDE_NAVIGATION|
                View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
        if (Build.VERSION.SDK_INT>=19){
            uiOptions |= 0x00001000;
        }else{
            uiOptions |= View.SYSTEM_UI_FLAG_LOW_PROFILE;
        }
        window.getDecorView().setSystemUiVisibility(uiOptions);
    }

    //    方法一
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
    }

    @Override
    protected void onResume() {
        super.onResume();
        LogUtils.i("BaseActivity", getClass().getSimpleName() + " onResume");
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        LogUtils.i("BaseActivity", getClass().getSimpleName() + " onPause");
        MobclickAgent.onPause(this);
    }





    /**
     * 屏幕常亮
     */
    public void bright() {
        try {
            wl.acquire();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 取消常亮
     */
    public void cancelBright() {
        try {
            wl.release();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 初始化子类布局
     *
     * @param layoutId
     */
    private void initContent(int layoutId) {
        if (layoutId != 0) {
            View layoutView = LayoutInflater.from(this).inflate(layoutId, frameLayout, false);
            frameLayout.addView(layoutView);
            unbinder = ButterKnife.bind(this, frameLayout);
            initView();
        } else {
            throw new IllegalStateException("请初始化布局");
        }
    }

    /**
     * 初始化布局
     */
    protected abstract void initView();


    /**
     * 初始化子类布局
     */
    protected abstract int getLayoutId();


    /**
     * 得到上个页面传来的数据
     *
     * @param intent
     */
    protected abstract void getIntentData(Intent intent);


    /**
     * 显示加载框
     */
    protected void showLoadingDialog() {
        if (mLoadingDialog != null)
            mLoadingDialog.show();
    }

    /**
     * 显示带有消息的加载框
     *
     * @param str
     */
    public void showLoadingDialog(String str) {
        if (mLoadingDialog != null) {
            TextView tv = (TextView) mLoadingDialog.findViewById(R.id.tv_load_dialog);
            tv.setText(str);
            mLoadingDialog.show();
        }
    }

    /**
     * 隐藏加载框
     */
    public void hideLoadingDialog() {
        if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
            Context context = ((ContextWrapper)mLoadingDialog.getContext()).getBaseContext();
            if(context instanceof Activity) {
                if (!((Activity)context).isFinishing() && !((Activity)context).isDestroyed()) {
                    mLoadingDialog.dismiss();
                }
            }
        }
    }

    /**
     * 显示提示消息的提示框
     *
     * @param text
     */
    protected void showHintDialog(String text) {
        if (mHintDialog != null) {
            TextView tv = mHintDialog.findViewById(R.id.tv_load_dialog);
            tv.setText(text);
            mHintDialog.show();
            if (handler!= null) {
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        hideHintDialog();
                    }
                },1500);
            }
        }
    }

    /**
     * 隐藏加载框
     */
    protected void hideHintDialog() {
        if (mHintDialog != null && mHintDialog.isShowing()) {
            Context context = ((ContextWrapper)mHintDialog.getContext()).getBaseContext();
            if(context instanceof Activity) {
                if (!((Activity)context).isFinishing() && !((Activity)context).isDestroyed()) {
                    mHintDialog.dismiss();
                }
            }
        }
    }

    /**
     * 吐司
     *
     * @param msg
     */
    protected void showToast(String msg) {
        ToastUtils.showToast(msg);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbinder.unbind();
        if (handler != null) {
            handler=null;
        }
        ActivityManagers.getInstance().finishActivity(this);
    }



    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {

                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        // 必不可少，否则所有的组件都不会有TouchEvent了
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

    public boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击的是输入框区域，保留点击EditText的事件
                return false;
            } else {
                return true;
            }
        }
        return false;
    }




}
